package com.yunlankeji.stemcells.utils;

import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.yunlankeji.stemcells.BaseApplication;
import com.yunlankeji.stemcells.entity.City;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author yang
 */
public  class AssetsUtils {

    public static City readJson(){
        return  new Gson().fromJson(readStringFromAssets(),City.class);
    }

    private static String readStringFromAssets() {
        AssetManager assetManager = BaseApplication.getAppContext().getAssets();
        InputStream inputStream = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        StringBuffer sb = new StringBuffer();
        try {
            inputStream = assetManager.open("city.json");
            isr = new InputStreamReader(inputStream);
            br = new BufferedReader(isr);

            sb.append(br.readLine());
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append("\n" + line);
            }

            br.close();
            isr.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }

}
